import { EventData, EventListener } from './Events';

class EventEmitter {
  private listeners: Map<string, Set<EventListener>>;
  constructor() {
    this.listeners = new Map();
    // console.log('🆕 EventEmitter: 创建新的EventEmitter实例');  
  }

  subscribe(channel: string, listener: EventListener): () => void {
    if (!this.listeners.has(channel)) {
      this.listeners.set(channel, new Set());
    }
    this.listeners.get(channel)?.add(listener);
    return () => this.unsubscribe(channel, listener);
  }

  private unsubscribe(channel: string, listener: EventListener): void {
    const channelListeners = this.listeners.get(channel);
    if (channelListeners) {
      channelListeners.delete(listener);
      if (channelListeners.size === 0) {
        this.listeners.delete(channel);
      } else {
        // console.log(`🗑️ EventEmitter: 频道 ${channel} 剩余监听器数量: ${channelListeners.size}`);
      }
    }
  }

  emit(channel: string, type: string, data: any): void {
    const eventData: EventData = { type, data, timestamp: Date.now() };
    const listeners = this.listeners.get(channel);
    listeners?.forEach(listener => {
      try {
        listener(eventData);
      } catch (error) {
        console.error(`Error in event listener for channel ${channel}:`, error);
      }
    });
  }

  // 清理所有监听器
  clear(): void {
    this.listeners.clear();
  }
}

// 在 globalThis 上持久化单例，避免 HMR 重置
declare global {
  var __eventEmitter: EventEmitter;
}

const emitterSingleton: EventEmitter =
  globalThis.__eventEmitter ||
  (globalThis.__eventEmitter = new EventEmitter());

export const eventEmitter = emitterSingleton;